//
//  PhotoModelDataService.swift
//  FileManager-NSCache-HttpDownload
//
//  Created by DaleGuo on 2023/9/19.
//

import Combine
import Foundation

// Service作为公用,处理下载的数据
class PhotoModelDataService {
    static let instance = PhotoModelDataService()

    @Published var photoModels: [PhotoModel] = []

    var cancellables = Set<AnyCancellable>()

    private init() {
        downloadData()
    }

    func downloadData() {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/photos") else {
            return
        }
        
        print("Downloading in Service")

        URLSession.shared.dataTaskPublisher(for: url)
            .subscribe(on: DispatchQueue.global(qos: .background)) //子线程获取数据
            .receive(on: DispatchQueue.main) //主线程绑定数据
            .tryMap(handleOutput) //尝试转换response为HttpUrlResponse
            .decode(type: [PhotoModel].self, decoder: JSONDecoder())
            .sink { completion in
                switch completion {   //由于trymap可能throws 所以sink有多个completion
                case .finished:
                    break
                case .failure(let error):
                    print("Download data errow : \(error)")
                }
            } receiveValue: { [weak self] returnedPhotoModels in
                self?.photoModels = returnedPhotoModels
            }
            .store(in: &cancellables)
    }

    private func handleOutput(output: URLSession.DataTaskPublisher.Output) throws -> Data {
        guard
            let response = output.response as? HTTPURLResponse,
            response.statusCode >= 200, response.statusCode < 300
        else {
            throw URLError(.badServerResponse)
        }

        return output.data
    }
}
